package com.chen.demo.simple.repository.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.demo.simple.command.query.BookPageQuery;
import com.chen.demo.simple.command.query.BookQuery;
import com.chen.demo.simple.domain.entity.Book;
import com.chen.demo.simple.repository.BookRepository;
import com.chen.demo.simple.repository.dao.BookDao;
import com.chen.demo.simple.repository.mapper.BookMapper;
import com.chen.winnerframework.util.PageUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@RequiredArgsConstructor
public class BookRepositoryImpl implements BookRepository {

    private final BookDao bookDao;
    private final BookMapper bookMapper;

    @Override
    public void insertBook(Book book) {
        bookDao.save(book);
    }

    @Override
    public void deleteBookById(Integer id) {
        bookDao.deleteById(id);
    }

    @Override
    public void updateBookById(Book book) {
        bookDao.save(book);
    }

    @Override
    public List<Book> selectBookByName(BookQuery query) {
        return bookMapper.selectList(Wrappers.<Book>lambdaQuery()
                .like(StringUtils.isNotBlank(query.getName()), Book::getName, query.getName()));
    }

    @Override
    public Page<Book> pageQueryBook(BookPageQuery pageQuery) {
        String name = pageQuery.getQuery().getName();
        return bookMapper.selectPage(PageUtil.build(pageQuery), Wrappers.<Book>lambdaQuery()
                .eq(StringUtils.isNotBlank(name), Book::getName, name));
    }
}
